package com.sniff.atp.modules.test.filter;

import com.ckbs.user.client.dto.resp.ManageLoginRespDTO;
import com.ckbs.user.client.utils.JwtUtil;
import com.ckbs.user.common.execption.CkbsException;
import com.sniff.atp.constant.RedisPrefix;
import com.sniff.atp.manage.RedisManage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @BelongsProject: sniff-atp
 * @BelongsPackage: com.sniff.atp.modules.test.filter
 * @Author: zxy
 * @CreateTime: 2023-12-12 13:34
 * @Description: 过滤校验token
 * @Version: 1.0
 */
@Slf4j
@WebFilter(filterName = "HeadFilter", urlPatterns = {"/ops/*"})
public class HeadFilter implements Filter {
    @Autowired
    private RedisManage redisManage;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setCharacterEncoding("UTF-8");

        try {
            String requestURI = request.getRequestURI();

            if (requestURI.contains("/login") || requestURI.contains("login.html") || requestURI.contains("login.do")){
                filterChain.doFilter(request, response);
            }else {
                String token = request.getHeader("token");
                if (token == null || token.length() == 0){
                    response.getWriter().write("{\"code\": \"20001\",\"msg\":\"token为空\"}");
                }else{
                    try {
                        ManageLoginRespDTO manageDTO= JwtUtil.getManageDTO(token);
                        String key = redisManage.getKey(RedisPrefix.SNIFF_USER_TOKEN + manageDTO.getUserId());
                        if (key == null || key.length() == 0){
                            response.getWriter().write("{\"code\": \"20002\",\"msg\":\"token失效\"}");
                        }
                    }catch (CkbsException e){
                        response.getWriter().write("{\"code\": \""+e.getCode()+"\",\"msg\":\""+e.getMsg()+"\"}");
                    }
                }
                filterChain.doFilter(request, response);
            }
        }catch (Exception e){
            log.error("过滤校验token异常");
        }
    }
}
